package com.sunday.fangdaifu.widgets;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.sunday.fangdaifu.model.PieData;


import java.util.Arrays;
import java.util.List;


/**
 *
 */

public class HollowPieNewChart extends View {
    /**
     * 视图的宽和高
     */
    private int mTotalWidth, mTotalHeight;
    /**
     * 绘制饼状图的圆的半径
     */
    private float mOutRadius;
    //宽度
    private int mOutStrokeWidth = dp2px(10);

    private float mCirRadius;//外围圆环半径
    private int mCircleStrokeWith = dp2px(7);//外围圆环宽度

    private int gapWidth = dp2px(7);//圆环的中间间隙

    private Paint mPaint, mLinePaint, mTextPaint;

    /**
     * 扇形的绘制区域
     */
    private RectF mOutRectF;
    /**
     * 点击之后的扇形的绘制区域
     */
    private RectF mRectFTouch;

    private List<PieData> mDataList;
    /**
     * 所有的数据加起来的总值
     */
    private float mTotalValue;
    /**
     * 起始角度的集合
     */
    private float[] angles;

    private Canvas mCenterCanvas;
    private Bitmap mCenterBitmap;

    /**
     * 手点击的部分的position
     */
    private int position = -1;
    /**
     * 点击监听
     */
    private OnItemPieClickListener mOnItemPieClickListener;

    public void setOnItemPieClickListener(OnItemPieClickListener onItemPieClickListener) {
        mOnItemPieClickListener = onItemPieClickListener;
    }

    public void setmOnCenter(OnCenterDraw mOnCenter) {
        this.mOnCenter = mOnCenter;
    }

    public interface OnItemPieClickListener {
        void onClick(int position);
    }

    public HollowPieNewChart(Context context) {
        super(context);
        init(context);
    }

    public HollowPieNewChart(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public HollowPieNewChart(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mOutRectF = new RectF();
        mRectFTouch = new RectF();

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);

        mLinePaint = new Paint();
        mLinePaint.setAntiAlias(true);
        mLinePaint.setStyle(Paint.Style.FILL);
        mLinePaint.setStrokeWidth(4);
        mLinePaint.setColor(Color.BLACK);

        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setStyle(Paint.Style.FILL);
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setTextSize(26);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mTotalWidth = w - getPaddingLeft() - getPaddingRight();
        mTotalHeight = h - getPaddingTop() - getPaddingBottom();

        mOutRadius = (float) (Math.min(mTotalWidth, mTotalHeight) / 2 * 0.6);
        mCirRadius = mOutRadius + mOutStrokeWidth / 2 + mCircleStrokeWith / 2 + gapWidth;

        mRectFTouch.left = mOutRectF.left = -mOutRadius;
        mRectFTouch.top = mOutRectF.top = -mOutRadius;
        mRectFTouch.right = mOutRectF.right = mOutRadius;
        mRectFTouch.bottom = mOutRectF.bottom = mOutRadius;

//        mRectFTouch.left = -mOutRadius-16;
//        mRectFTouch.top = -mOutRadius-16;
//        mRectFTouch.right = mOutRadius+16;
//        mRectFTouch.bottom = mOutRadius+16;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.save();
        super.onDraw(canvas);
        if (mDataList == null)
            return;
        canvas.translate(mTotalWidth / 2, mTotalHeight / 2);
        //绘制外围的圆圈
        mPaint.setColor(0xfff3f5f6);
        mPaint.setStrokeWidth(mCircleStrokeWith);
        mPaint.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(0, 0, mCirRadius, mPaint);

        //绘制饼图的每块区域
        drawPiePath(canvas);
        canvas.restore();
    }

    /**
     * 绘制饼图的每块区域 和文本
     *
     * @param canvas
     */
    private void drawPiePath(Canvas canvas) {
        //起始地角度
        float startAngle = 0;
        for (int i = 0; i < mDataList.size(); i++) {
            float sweepAngle;
            if (mTotalValue == 0) {
                sweepAngle = 360 / mDataList.size()+1;//每个扇形的角度
            } else {
                if (mDataList.get(i).getValue() == 0) {
                    sweepAngle = 3;
                } else {
                    sweepAngle = mDataList.get(i).getValue() / mTotalValue * 360+1;
                }
            }//每个扇形的角度
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(mDataList.get(i).getColor());
            mPaint.setStrokeWidth(mOutStrokeWidth);
            if (position - 1 == i) {
                canvas.drawArc(mRectFTouch, startAngle, sweepAngle, true, mPaint);
            } else {
                canvas.drawArc(mOutRectF, startAngle, sweepAngle, true, mPaint);
            }

            Log.i("toRadians", (startAngle + sweepAngle / 2) + "****" + Math.toRadians(startAngle + sweepAngle / 2));
            //确定直线的起始和结束的点的位置
//            float pxs = (float) ((mOutRadius+DensityUtil.dip2px(getContext(),20))*Math.cos(Math.toRadians(startAngle+sweepAngle/2)));
//            float pys = (float) ((mOutRadius+DensityUtil.dip2px(getContext(),20))*Math.sin(Math.toRadians(startAngle+sweepAngle/2)));
//            float pxt = (float) (((mOutRadius+DensityUtil.dip2px(getContext(),20))+30)*Math.cos(Math.toRadians(startAngle+sweepAngle/2)));
//            float pyt = (float) (((mOutRadius+DensityUtil.dip2px(getContext(),20))+30)*Math.sin(Math.toRadians(startAngle+sweepAngle/2)));
            float pxs = (float) ((mOutRadius + mOutStrokeWidth / 2) * Math.cos(Math.toRadians(startAngle + sweepAngle / 2)));
            float pys = (float) ((mOutRadius + mOutStrokeWidth / 2) * Math.sin(Math.toRadians(startAngle + sweepAngle / 2)));
            float pxt = (float) ((mOutRadius + mOutStrokeWidth / 2 + gapWidth + mCircleStrokeWith) * Math.cos(Math.toRadians(startAngle + sweepAngle / 2)));
            float pyt = (float) ((mOutRadius + mOutStrokeWidth / 2 + gapWidth + mCircleStrokeWith) * Math.sin(Math.toRadians(startAngle + sweepAngle / 2)));

            angles[i] = startAngle;
            startAngle += sweepAngle + 1;
            //startAngle += sweepAngle;
            mLinePaint.setColor(mDataList.get(i).getColor());
            //绘制线
            canvas.drawLine(pxs, pys, pxt, pyt, mLinePaint);
            //绘制延伸线 判断象限 二三象限要做减法
            float pxt1;
            Rect rect;
            String str = String.format("%1$s %2$d", mDataList.get(i).getName(), mDataList.get(i).getValue());
            if (pxt < 0) {
                pxt1 = pxt - dp2px(20);
                rect = new Rect((int) (pxt1 - mTextPaint.measureText(str) - dp2px(16)), (int) (pyt - dp2px(13)), (int) (pxt1), (int) (pyt + dp2px(13)));

            } else {
                pxt1 = pxt + dp2px(20);
                rect = new Rect((int) (pxt1), (int) (pyt - dp2px(13)), (int) (pxt1 + mTextPaint.measureText(str) + dp2px(16)), (int) (pyt + dp2px(13)));

            }
            canvas.drawLine(pxt, pyt, pxt1, pyt, mLinePaint);
            mPaint.setStyle(Paint.Style.FILL);
            canvas.drawRect(rect, mPaint);
            mTextPaint.setColor(Color.WHITE);
            canvas.drawText(str, rect.left + dp2px(8), pyt + dp2px(3), mTextPaint);
        }
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(0, 0, mOutRadius - mOutStrokeWidth / 2, mPaint);
        //绘制中间内容
        /*mTextPaint.setColor(0xff333333);
        mTextPaint.setTextSize(50);
        String total= String.valueOf(mTotalValue);
        canvas.drawText(total,-mTextPaint.measureText(total)/2,-dp2px(4),mTextPaint);
        mTextPaint.setColor(0xff808080);
        mTextPaint.setTextSize(26);
        String extraTotal="总任务数";
        canvas.drawText(extraTotal,-mTextPaint.measureText(extraTotal)/2,dp2px(10),mTextPaint);*/
        if (mOnCenter != null) {
            mOnCenter.draw(canvas, mTextPaint);
        }
    }

    public void setDataList(List<PieData> dataList) {
        this.mDataList = dataList;
        mTotalValue = 0;
        for (PieData pieData : mDataList) {
            mTotalValue += pieData.getValue();
        }
        angles = new float[mDataList.size()];
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        /*switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                float x = event.getX() - (mTotalWidth / 2);
                float y = event.getY() - (mTotalHeight / 2);
                float touchAngle = 0;
                if (x < 0 && y < 0) {  //2 象限
                    touchAngle += 180;
                } else if (y < 0 && x > 0) {  //1象限
                    touchAngle += 360;
                } else if (y > 0 && x < 0) {  //3象限
                    touchAngle += 180;
                }
                //Math.atan(y/x) 返回正数值表示相对于 x 轴的逆时针转角，返回负数值则表示顺时针转角。
                //返回值乘以 180/π，将弧度转换为角度。
                touchAngle += Math.toDegrees(Math.atan(y / x));
                if (touchAngle < 0) {
                    touchAngle = touchAngle + 360;
                }
                float touchRadius = (float) Math.sqrt(y * y + x * x);
                if (touchRadius < mOutRadius) {
                    if (angles != null)
                        position = -Arrays.binarySearch(angles, (touchAngle)) - 1;
                    invalidate();
                    if (mOnItemPieClickListener != null) {
                        mOnItemPieClickListener.onClick(position - 1);
                    }
                }
                break;
        }*/
        return super.onTouchEvent(event);
    }

    /**
     * dp 2 px
     *
     * @param dpVal
     */
    protected int dp2px(int dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, getResources().getDisplayMetrics());
    }

    private OnCenterDraw mOnCenter;

    public interface OnCenterDraw {
        public void draw(Canvas canvas, Paint paint);
    }


}